<template>
  <div class="category-container">
    <el-card class="category-card" shadow="hover">
      <div class="category-header">
        <div class="category-title">
          <i class="el-icon-notebook-2"></i> 课程分类管理
        </div>
        <el-button type="primary" size="medium" icon="el-icon-plus" @click="openAddDialog(null)">
          添加顶级分类
        </el-button>
      </div>

      <el-row :gutter="24" class="content-row">
        <!-- 左侧树结构 - 比例增大 -->
        <el-col :span="10">
          <el-card class="tree-card" shadow="never" body-style="padding:0">
            <div class="tree-header">
              <div class="tree-title">
                <i class="el-icon-folder"></i> 课程分类树
              </div>
              <el-input v-model="filterText" placeholder="搜索分类..." prefix-icon="el-icon-search" size="medium" clearable
                class="search-input" />
            </div>
            <el-divider></el-divider>
            <div style="max-height: 650px; overflow-y: auto; padding: 0 12px;">
              <el-tree v-loading="loading" ref="tree" :data="categories" :props="treeProps" node-key="id"
                :expand-on-click-node="false" :highlight-current="true" :filter-node-method="filterNode"
                default-expand-all @node-click="handleNodeClick" class="custom-tree">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span>
                    <i :class="data.children ? 'el-icon-folder' : 'el-icon-document'"></i>
                    {{ data.name || data.title }}
                  </span>
                  <span class="node-actions">

                    <el-tooltip v-if="!findParentId(data.id)" content="添加子类" placement="top">
                      <el-button size="mini" type="text" icon="el-icon-plus"
                        @click.stop="() => openAddDialog(data)"></el-button>
                    </el-tooltip>
                    <el-tooltip content="编辑" placement="top">
                      <el-button size="mini" type="text" icon="el-icon-edit"
                        @click.stop="() => openEditDialog(data)"></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                      <el-button size="mini" type="text" icon="el-icon-delete" style="color: #F56C6C"
                        @click.stop="() => deleteCategory(data)"></el-button>
                    </el-tooltip>
                  </span>
                </span>
              </el-tree>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧详情 - 比例减小 -->
        <el-col :span="14">
          <el-card class="details-card" shadow="never" body-style="padding:20px">
            <div class="details-header">
              <div class="details-title">
                <i class="el-icon-info"></i> 课程详情
              </div>
              <el-tag v-if="selectedCategory && !selectedCategory.children" type="info">
                ID: {{ selectedCategory.id }}
              </el-tag>
            </div>
            <el-divider></el-divider>
            <div v-if="selectedCategory && !selectedCategory.children" class="details-content">
              <!-- 修改后的描述列表 -->
              <div class="descriptions-container">
                <!-- 模板示例 -->
                <el-descriptions :column="1" border class="fixed-descriptions" :contentStyle="{ textAlign: 'center' }">
                  <el-descriptions-item label="课程名称" label-class-name="desc-label">
                    <el-tag type="success" class="fixed-tag">课程名称</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="所属分类" label-class-name="desc-label">
                    <el-tag type="success" class="fixed-tag">所属分类</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="创建时间" label-class-name="desc-label">
                    <el-tag type="success" class="fixed-tag">创建时间</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="修改时间" label-class-name="desc-label">
                    <el-tag type="success" class="fixed-tag">修改时间</el-tag>
                  </el-descriptions-item>
                </el-descriptions>

                <!-- 动态数据 -->
                <el-descriptions :column="1" border class="fixed-descriptions" :contentStyle="{ textAlign: 'center' }">
                  <el-descriptions-item label="课程名称" label-class-name="desc-label">
                    <div class="fixed-content">{{ selectedCategory.title || '无' }}</div>
                  </el-descriptions-item>
                  <el-descriptions-item label="所属分类" label-class-name="desc-label">
                    <div class="fixed-content">{{ selectedCategory.parentName || '无' }}</div>
                  </el-descriptions-item>
                  <el-descriptions-item label="创建时间" label-class-name="desc-label">
                    <div class="fixed-content">{{ formatDate(selectedCategory.gmtCreate) }}</div>
                  </el-descriptions-item>
                  <el-descriptions-item label="修改时间" label-class-name="desc-label">
                    <div class="fixed-content">{{ formatDate(selectedCategory.gmtModified) }}</div>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
            <div v-else-if="selectedCategory && selectedCategory.children" class="empty-details">
              <el-empty description="当前选择的是分类目录，请选择具体课程查看详情"></el-empty>
            </div>
            <div v-else class="empty-details">
              <el-empty description="请从左侧选择课程查看详细信息"></el-empty>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 添加/编辑分类对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
        <el-form :model="form" :rules="rules" ref="formRef">
          <el-form-item label="分类名称" label-width="100px" prop="name">
            <el-input v-model="form.name" placeholder="请输入分类名称" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { getCategoryList } from '@/api/edu/subject'
import { addSubject } from '@/api/edu/subject'
import { deleteSubject } from '@/api/edu/subject'
import { updateSubject } from '@/api/edu/subject'

export default {
  data() {
    return {
      categories: [],
      loading: false,
      treeProps: {
        children: 'children',
        label: data => data.name || data.title
      },
      selectedCategory: null,
      dialogVisible: false,
      dialogTitle: '',
      filterText: '',
      form: {
        id: null,
        name: '',
        parentId: null
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchCategories()
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    formatDate(time) {
      if (!time) return '无'
      const date = new Date(time)
      const Y = date.getFullYear()
      const M = ('0' + (date.getMonth() + 1)).slice(-2)
      const D = ('0' + date.getDate()).slice(-2)
      const h = ('0' + date.getHours()).slice(-2)
      const m = ('0' + date.getMinutes()).slice(-2)
      const s = ('0' + date.getSeconds()).slice(-2)
      return `${Y}-${M}-${D} ${h}:${m}:${s}`
    },
    async fetchCategories() {
      this.loading = true
      try {
        const response = await getCategoryList()
        if (response.code === 20000) {
          this.categories = response.data
        } else {
          this.$message.error(response.message || '获取分类列表失败')
        }
      } catch (error) {
        this.$message.error('请求分类列表失败')
      } finally {
        this.loading = false
      }
    },

    filterNode(value, data) {
      if (!value) return true
      const label = data.name || data.title
      return label.toLowerCase().includes(value.toLowerCase())
    },

    handleNodeClick(data) {
      this.selectedCategory = {
        ...data,
        parentName: this.findParentName(data.id)
      }
    },

    openAddDialog(clickedNode) {
      // 设置对话框标题
      this.dialogTitle = clickedNode ? `添加子分类（${clickedNode.name || clickedNode.title}）` : '添加顶级分类';

      // 关键逻辑：如果点击的是"添加子类"按钮，parentId=当前节点id；否则parentId=0
      this.form = {
        id: null,
        name: '',
        parentId: clickedNode ? clickedNode.id : 0 // 这里是最重要的修改！
      };

      this.dialogVisible = true;
      this.$nextTick(() => this.$refs.formRef?.clearValidate());
    },

    openEditDialog(category) {
      this.dialogTitle = '编辑分类'
      this.form = {
        id: category.id,
        name: category.name || category.title,
        parentId: this.findParentId(category.id)
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate()
      })
    },

    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return;

        if (this.form.id) {
          // 更新现有分类
          this.updateCategory({
            id: this.form.id,
            name: this.form.name.trim()
          });
        } else {
          // 添加新分类（保持原有逻辑）
          this.addCategory({
            name: this.form.name.trim(),
            parentId: this.form.parentId
          });
        }
      });
    },

    // 添加一级分类
    // 修改后的添加分类方法
    async addCategory(data) {
      try {
        this.loading = true;
        const response = await addSubject(data);

        if (response.code === 20000) {
          this.$message.success(data.parentId === 0 ? '顶级分类添加成功' : '子分类添加成功');
          this.fetchCategories(); // 刷新分类树
        } else {
          this.$message.error(response.message || '操作失败');
        }
      } catch (error) {
        this.$message.error('请求失败: ' + (error.response?.data?.message || error.message));
      } finally {
        this.loading = false;
      }
    },

    async updateCategory({ id, name }) {
      try {
        this.loading = true;

        // 1. 调用API更新分类
        const response = await updateSubject({ id, name });

        // 2. 处理响应
        if (response.code === 20000) {
          this.$message.success('分类更新成功');
          this.fetchCategories(); // 刷新分类树
          this.dialogVisible = false; // 关闭对话框
        } else {
          this.$message.error(response.message || '更新失败');
        }
      } catch (error) {
        this.$message.error('请求失败: ' + (error.response?.data?.message || error.message));
      } finally {
        this.loading = false;
      }
    },

    deleteCategory(category) {
      this.$confirm(`确定要删除分类 "${category.name || category.title}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // API调用
        // alert('1313231')
        deleteSubject(category.id).then(response => {
          this.fetchCategories();
          this.$message.success('删除成功')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    findCategoryById(id, list = this.categories) {
      for (const item of list) {
        if (item.id === id) return item
        if (item.children) {
          const found = this.findCategoryById(id, item.children)
          if (found) return found
        }
      }
      return null
    },

    findParentId(childId, list = this.categories, parentId = null) {
      for (const item of list) {
        if (item.id === childId) return parentId
        if (item.children) {
          const found = this.findParentId(childId, item.children, item.id)
          if (found !== null) return found
        }
      }
      return null
    },

    findParentName(childId) {
      const parentId = this.findParentId(childId)
      const parent = this.findCategoryById(parentId)
      return parent ? (parent.name || parent.title) : null
    }
  }
}
</script>

<style scoped lang="scss">
.category-container {
  padding: 20px;
  height: calc(100vh - 60px);
  background-color: #f5f7fa;

  .category-card {
    height: 100%;
    display: flex;
    flex-direction: column;
    border-radius: 8px;
    border: 1px solid #ebeef5;

    .category-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding: 15px 20px;
      background: linear-gradient(90deg, #f0f7ff, #ffffff);
      border-radius: 8px 8px 0 0;

      .category-title {
        font-size: 22px;
        font-weight: bold;
        color: #409EFF;
        display: flex;
        align-items: center;

        i {
          margin-right: 10px;
          font-size: 24px;
        }
      }
    }
  }

  .content-row {
    flex: 1;
    min-height: 0;
    padding: 0 20px;
    margin-bottom: 20px;

    .el-col {
      height: 100%;
      display: flex;
      flex-direction: column;
    }
  }

  .tree-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 0;
    border: 1px solid #e6e6e6;

    .tree-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 20px;
      background: #f8fafc;

      .tree-title {
        font-size: 18px;
        font-weight: bold;
        color: #333;
        display: flex;
        align-items: center;

        i {
          margin-right: 8px;
          color: #409EFF;
        }
      }

      // .search-input {
      //   width: 220px;

      //   ::v-deep .el-input__inner {
      //     border-radius: 20px;
      //   }
      // }
      .search-input {
        width: 250px;
        transition: all 0.3s;

        &:hover {
          transform: scale(1.05);
          /* 悬浮轻微放大 */
        }

        ::v-deep .el-input__inner {
          border-radius: 20px;
          background: linear-gradient(90deg, #f0f7ff, #ffffff);
          /* 渐变背景 */
          //border: 3px solid #c6e2ff;
          height: 38px;
          font-weight: 500;
          /* 加粗字体 */
        }
      }
    }

    .el-divider {
      margin: 0;
    }
  }

  .custom-tree {
    flex: 1;
    overflow: auto;
    font-size: 16px;
    padding: 10px 15px;

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 5px 0;
      transition: all 0.3s;

      &:hover {
        background-color: #f0f7ff;
        border-radius: 4px;
      }

      i {
        margin-right: 8px;
        color: #67C23A;

        &.el-icon-folder {
          color: #E6A23C;
        }
      }

      .node-actions {
        opacity: 0;
        transition: opacity 0.3s;

        .el-button {
          padding: 5px;
          margin-left: 5px;
        }
      }

      &:hover .node-actions {
        opacity: 1;
      }
    }

    .el-tree-node.is-current>.el-tree-node__content .custom-tree-node {
      background-color: #ecf5ff;
      border-radius: 4px;
    }
  }

  .details-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 0;
    border: 1px solid #e6e6e6;
    margin-left: 20px;

    .details-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 15px;

      .details-title {
        font-size: 18px;
        font-weight: bold;
        color: #333;
        display: flex;
        align-items: center;

        i {
          margin-right: 8px;
          color: #409EFF;
        }
      }
    }

    .el-divider {
      margin: 0 0 15px 0;
    }
  }

  .details-content {
    padding: 10px;

    .descriptions-container {
      display: flex;
      gap: 20px;

      .fixed-descriptions {
        width: 300px;

        ::v-deep .el-descriptions__label {
          width: 100px;
          text-align: right;
          padding-right: 12px;
          font-weight: bold;
          color: #606266;
        }

        ::v-deep .el-descriptions__content {
          width: 200px;
        }
      }

      .fixed-tag {
        width: 180px;
        text-align: center;
        font-size: 16px;
        padding: 0 10px;
        height: 32px;
        line-height: 32px;
        margin-bottom: 20px !important;
      }

      .fixed-content {
        width: 180px;
        text-align: center;
        padding: 6px 0;
        font-size: 16px;
        margin-bottom: 20px !important;
      }
    }
  }

  .empty-details {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: #909399;

    .el-empty {
      padding: 40px 0;
    }
  }

  .dialog-footer {
    text-align: right;
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

</style>

